# standard format 

module TrafficConvert
  # accept kb/k, mb/m, gb/g without case, others will be treated as byte
  # it will always return integer as decimal for bytes is meaningless
  def traffic_flow_from_params flow
    flow = flow.to_s.delete(' ').upcase

    units = ['K', 'M', 'G']
    units.each_index do |i|
      if flow.end_with? units[i], units[i] + 'B'
        flow = flow.to_f * 1024 ** (i + 1)
        break
      end
    end
    flow.to_i
  end

  def traffics_friendly_format traffic_count_by_byte
    return traffic_count_by_byte if traffic_count_by_byte == "NA"
    # return -1 if not limit
    return traffic_count_by_byte if traffic_count_by_byte == -1

    # May be it's done already?
    return traffic_count_by_byte if traffic_count_by_byte.to_s.upcase.end_with? ['B', 'K', 'M', 'G']

    # change it to integer to prevent error
    traffic_count_by_byte = traffic_count_by_byte.to_i

    # return zero to prevent compute error
    return 0 if traffic_count_by_byte <= 0

    level = [Math.log(traffic_count_by_byte, 1024).to_i, 3].min
    # without this, bytes will become float format according to the last statement
    return [traffic_count_by_byte, 'B'].join(" ") if level == 0

    units = ['KB', 'MB', 'GB']
    [(traffic_count_by_byte.to_f/(1024**level)).round(5).to_s, units[level - 1]].join(" ")
  end
end